package testJdk.thread.testRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author Created by cyd on 2021-03-29 12:17:23
 * @Description : Executors测试获取线程池工厂
 * <p>
 * 有三种工厂，并且每种工厂都有两种重载的形式
 */
public class MyTest01 {
    public static void main(String[] args) {
        // test01();
        test02();
    }

    private static void test02() {
        // 使用工厂类获取线程池对象,线程池中线程的生成规则可以通过匿名对象指定
        ExecutorService es = Executors.newCachedThreadPool(new ThreadFactory() {
            private int i;

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "自定义线程名称-" + i++);
            }
        });
        for (int i = 1; i <= 10; i++) {
            es.submit(new MyRunnable(i));
        }
    }

    private static void test01() {
        // 使用工厂类获取线程池对象
        ExecutorService es = Executors.newCachedThreadPool();
        for (int i = 1; i <= 10; i++) {
            es.submit(new MyRunnable(i));
        }
    }
}


class MyRunnable implements Runnable {
    private final int id;

    public MyRunnable(int id) {
        this.id = id;
    }

    /**
     * 获取线程的名称，并打印一句话
     */
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + "-执行了任务:" + id);
    }
}
